package com.gupao.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class ProcessorHander implements Runnable{

    private Socket socket;

    private Map<String,Object> handerMap;

    public ProcessorHander(Socket socket, Map<String,Object> handerMap) {
        this.socket = socket;
        this.handerMap = handerMap;
    }

    @Override
    public void run() {
        ObjectInputStream objectInputStream = null;
        ObjectOutputStream objectOutputStream =null;
        try {
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest request = (RpcRequest) objectInputStream.readObject();
            Object result = invoke(request);
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(result);
            objectOutputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(objectInputStream!=null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(objectOutputStream!=null){
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Object invoke(RpcRequest rpcRequest){
        try {
            Object[] params = rpcRequest.getParameters();
            Class<?>[] parameters = new Class[params.length];
            for (int i = 0; i < params.length ; i++) {
                parameters[i] = params[i].getClass();
            }
            //通过客户端请求的serviceName从handerMap中获取相应的service对象
            String serviceName = rpcRequest.getServiceName();
            String version = rpcRequest.getVersion();
            if(version!=null && !version.equals("")){
                serviceName += version;
            }
            Object service = handerMap.get(serviceName);
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(),parameters);
            return method.invoke(service,params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
